package org.dnd.rcp.editor.text;

import java.io.File;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.EditorPart;

/**
 * Kelas Editor
 * 
 * @author dendy
 * 
 */
public class Editor extends EditorPart implements TextSource {

	public final static String ID = "org.dnd.rcp.editor.editor";

	Text texts = null;

	boolean isDirty = false;

	File file = null;

	@Override
	public Text getText() {
		return texts;
	}

	@Override
	public void doSave(IProgressMonitor monitor) {
		setDirty(false);
	}

	@Override
	public void doSaveAs() {
	}

	@Override
	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		setSite(site);
		setInput(input);
	}

	@Override
	public boolean isDirty() {
		return isDirty;
	}

	@Override
	public boolean isSaveAsAllowed() {
		return true;
	}

	@Override
	public void createPartControl(Composite parent) {
		IEditorInput input = getEditorInput();

		IFile f = (IFile) input.getAdapter(IFile.class);
		if (f != null) {
			file = f.getLocation().toFile();
		}
		if (input instanceof EditorInput) {
			EditorInput fileInput = (EditorInput) input;
			file = fileInput.getFile();
		}

		Font font = new Font(null, "Courier New", 12, SWT.BOLD);
		texts = new Text(parent, SWT.MULTI | SWT.V_SCROLL | SWT.H_SCROLL);
		texts.setFont(font);
		texts.setBackground(new Color(null, 0, 0, 0));
		texts.setForeground(new Color(null, 0, 255, 0));
		texts.setText("");

		texts.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				isDirty = true;
				firePropertyChange(IEditorPart.PROP_DIRTY);
			}
		});
	}

	@Override
	public void setFocus() {
		texts.setFocus();
	}

	/**
	 * <p>
	 * Forces the dirty state of the editor to the dirty state passed as a
	 * parameter.
	 * <p>
	 * IMPORTANT NOTE: this method must be used with extreme caution to prevent
	 * from loosing unsaved changes.
	 * 
	 * @param pDirty
	 *            dirty state
	 */
	public void setDirty(boolean pDirty) {
		isDirty = pDirty;
		firePropertyChange(PROP_DIRTY);
	}

}
